class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ ans, start, end = 0, 0, 0 countDict = {} for c in s: end += 1 countDict[c] = countDict.get(c, 0) + 1 # countDict.get(c, 0)意思是:若c不存在直接返回0 while countDict[c] > 1: countDict[s[start]] -= 1 start += 1 ans = max(ans, end - start) return ans
优化思路:遇到重复的字母,直接跳到重复字母的后面一个,而不是像之前那样慢慢向右移动!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ used = {} max_length = start = 0 for i, c in enumerate(s): if c in used and start <= used[c]: start = used[c] + 1 else: max_length = max(max_length, i - start + 1)